package com.sj.purchase.modules.cost.service;

import com.sj.purchase.modules.cost.domain.Profit;
import com.sj.purchase.modules.cost.domain.ProfitId;
import com.sj.purchase.modules.cost.repository.ProfitRepository;
import com.sj.purchase.modules.cost.repository.imei.InventoryRepository;
import com.sj.purchase.modules.cost.service.order.OutOrderItemCostService;
import com.sj.purchase.modules.cost.utils.DoubleUtil;
import com.sj.purchase.modules.cost.views.out_order.OutOrderCostVO;
import com.sj.purchase.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: songkaizong
 * 18-1-9 下午5:22
 */
@Service
public class ProfitService {
    @Autowired
    private OutOrderItemCostService outOrderItemCostService;
    @Autowired
    private ProfitRepository profitRepository;
    @Autowired
    private InventoryRepository inventoryRepository;

    public void save(Date day) {
        List<OutOrderCostVO> outOrderCostVOS = outOrderItemCostService.search(null, DateUtils.getStartOfDay(day), DateUtils.getEndOfDay(day), null).getContent();
        Map<String, List<OutOrderCostVO>> map = outOrderCostVOS.stream().collect(Collectors.groupingBy(outOrderCostVO -> outOrderCostVO.getShopName()));
        List<Object[]> shopImeiList = inventoryRepository.countImeiGroupShop(DateUtils.getStartOfDay(day), DateUtils.getEndOfDay(day));
        Map<String, Integer> shopImeiMap = new HashMap<>();
        shopImeiList.stream().forEach(objects -> shopImeiMap.put(objects[0].toString(), Integer.valueOf(objects[1].toString())));
        map.forEach((shopName, outOrderCostVOS1) -> {
            final double[] imeiTotalProfit = {0};
            final double[] avgPriceProfit = {0};
            outOrderCostVOS1.forEach(o -> {
                imeiTotalProfit[0] += o.getProfit1();
                avgPriceProfit[0] += o.getProfit2();
            });
            int imeiNum = Optional.ofNullable(shopImeiMap.get(shopName)).orElse(0);
            profitRepository.save(new Profit(new ProfitId(day, shopName),
                    outOrderCostVOS1.size(),
                    DoubleUtil.format(imeiTotalProfit[0]),
                    DoubleUtil.format(avgPriceProfit[0]),
                    imeiNum));
        });
        if (map.size() == 0) {
            profitRepository.save(new Profit(new ProfitId(day, "三际手机采购网"), 0, 0.0, 0.0, 0));
            profitRepository.save(new Profit(new ProfitId(day, "三际数码官方旗舰店"), 0, 0.0, 0.0, 0));
        }
    }
}
